﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;

namespace ArrowWebParts
{
    public class Browser : LayoutsPageBase
    {
        /// <summary>
        /// <para>file: file selector mode</para>
        /// <para>folder: folder selector mode</para>
        /// </summary>
        private string mode;
        /// <summary>
        /// Client ID of the control that launched the Browser.
        /// </summary>
        private string callerID;

        private RadFileExplorer fileExplorer;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // telerik script manager
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            if (scriptManager == null)
            {
                scriptManager = new ScriptManager();
                this.Page.Form.Controls.AddAt(0, scriptManager);
            }

            mode = Request["type"];
            callerID = Request["ctrl"];
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // telerik security key
            Application["Telerik.Web.UI.Key"] = "{67478558-9047-49b5-A747-34E357943BF1}";

            // javascript block
            if (!Page.ClientScript.IsClientScriptBlockRegistered(GetType(), "TomasScript"))
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "TomasScript", CreateScriptBlock(callerID, mode), true);

            // file explorer panel
            Panel panel2 = new Panel();
            Form.Controls.Add(panel2);

            // file explorer
            fileExplorer = new RadFileExplorer();
            string[] paths = { SPContext.Current.Site.RootWeb.Url };
            //string[] paths = { "/" };
            fileExplorer.Configuration.ViewPaths = paths;
            fileExplorer.EnableCopy = false;
            fileExplorer.EnableCreateNewFolder = false;
            fileExplorer.EnableOpenFile = false;
            fileExplorer.Height = new Unit(400);
            fileExplorer.OnClientItemSelected = "OnClientItemSelected";
            if (mode == "folder")
            {
                fileExplorer.Configuration.ContentProviderTypeName =
                    typeof(SPFolderBrowserContentProvider).AssemblyQualifiedName;
                fileExplorer.OnClientFolderChange = "OnClientItemSelected";
            }
            else // mode == "file" assumed
            {
                fileExplorer.OnClientFileOpen = "OnClientFileOpen";
                fileExplorer.Configuration.ContentProviderTypeName =
                    typeof (SPFileBrowserContentProvider).AssemblyQualifiedName;
            }
            panel2.Controls.Add(fileExplorer);
            fileExplorer.ItemCommand += new RadFileExplorerEventHandler(fileExplorer_ItemCommand);

            // telerik ajax manager
            RadAjaxManager ajaxManager = RadAjaxManager.GetCurrent(this.Page);
            if (ajaxManager == null)
            {
                ajaxManager = new RadAjaxManager();
                ajaxManager.ID = "RadAjaxManager1";
                Form.Controls.Add(ajaxManager);
                this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);
            }

            // close button
            Table table = new Table();
            table.HorizontalAlign = HorizontalAlign.Right;
            Form.Controls.Add(table);
            TableRow row = new TableRow();
            table.Rows.Add(row);
            row.Cells.Add(new TableCell(){Width = new Unit(10)});
            TableCell cell = new TableCell();
            row.Cells.Add(cell);
            row.Cells.Add(new TableCell(){Width = new Unit(10)});
            cell.Height = new Unit(50);
            HtmlButton btnDone = new HtmlButton() {InnerText = "Done"};
            btnDone.Attributes["onclick"] = "window.close();";
            cell.Controls.Add(btnDone);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            // hide the size column
            if (fileExplorer.Grid.Columns.Count > 1)
                fileExplorer.Grid.Columns[1].Display = false;
        }

        void fileExplorer_ItemCommand(object sender, RadFileExplorerEventArgs e)
        {
            switch (e.Command)
            {
                case "UploadFile":
                case "MoveDirectory":
                case "CreateDirectory":
                case "DeleteDirectory":
                case "DeleteFile":
                case "MoveFile":
                    e.Cancel = true;
                    break;
            }
        }

        private static string CreateScriptBlock(string callerID, string mode)
        {
            string onClientFileOpen =
                @"
                function OnClientFileOpen(sender, args) 
                {
                    if (args.get_item().get_type() == Telerik.Web.UI.FileExplorerItemType.File)
                    {
                        OnClientItemSelected(sender, args);
                        window.close();
                    }
                }
                ";

            if (mode == "folder")
            {
                return
                @"
                function OnClientItemSelected(sender, args)
                {
                   //debugger;
                   var folderItem = args.get_item();
                   if (folderItem.get_type() == Telerik.Web.UI.FileExplorerItemType.Directory)
                       opener." + callerID + @"browser_FileItemClick(folderItem.get_name(), folderItem.get_path());
                }
                ";
            }
            // else mode == "file" assumed
            return
            @"
            function OnClientItemSelected(sender, args)
            {
               //debugger;
               var fileItem = args.get_item();
               if (fileItem.get_type() == Telerik.Web.UI.FileExplorerItemType.File)
                   opener." + callerID + @"browser_FileItemClick(fileItem.get_name(), fileItem.get_path());
            }
            " + "\n" + onClientFileOpen;
        }
    }
}
